package com.djhu.lock;
/**
 * Created by zw on 2017/12/13.
 */

import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * <p>
 * ---------------------------------
 */
public class RedisDistributedLock implements DistributedLock{

    private String lockKey = "defaultKey";

    private RedisTemplate redisTemplate;

    private int expireTime = 30;

    private static long DEFAULT_ACQUIRY_RESOLUTION_MILLIS = 100;

    private boolean lock0(String key,String value){
        if (redisTemplate.opsForValue().setIfAbsent(key,value)){
            redisTemplate.expire(key,expireTime,TimeUnit.SECONDS);
            return true;
        }
        return false;
    }

    @Override
    public boolean trylock() {
        String value = String.valueOf(System.currentTimeMillis());
        return lock0(this.lockKey,value);
    }

    @Override
    public boolean trylock(long time) throws InterruptedException {
        long timeout =  time;
        while (timeout > 0){
            if (trylock()){
                return true;
            }
            timeout -= DEFAULT_ACQUIRY_RESOLUTION_MILLIS;
            Thread.sleep(DEFAULT_ACQUIRY_RESOLUTION_MILLIS);
        }
        return false;
    }



    @Override
    public boolean trylock(String key) {
        String value = String.valueOf(System.currentTimeMillis());
        return lock0(key,value);
    }

    @Override
    public boolean trylock(String key, long time) throws InterruptedException {
        long timeout =  time;
        while (timeout > 0){
            if (trylock(key)){
                return true;
            }
            timeout -= DEFAULT_ACQUIRY_RESOLUTION_MILLIS;
            Thread.sleep(DEFAULT_ACQUIRY_RESOLUTION_MILLIS);
        }
        return false;
    }

    @Override
    public boolean unlock() {
        redisTemplate.delete(this.lockKey);
        return true;
    }

    @Override
    public boolean unlock(String key) {
        redisTemplate.delete(key);
        return false;
    }


    public RedisTemplate getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public int getExpireTime() {
        return expireTime;
    }

    public void setExpireTime(int expireTime) {
        this.expireTime = expireTime;
    }
}